package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

type User struct {
	Phone string `json:"phone" form:"phone"` //可绑定json或form形式的请求参数
	Age   int    `json:"age" form:"age"`
}

func main() {
	router := gin.Default()
	router.GET("/getParam", getParam)       //GET参数
	router.POST("/postParam", postParam)    //POST参数
	router.GET("/urlParam/:id", urlParam)   //路径参数，参数名=ID
	router.GET("/structParam", structParam) //将参数设置到结构体，支持GET和POST

	router.Run(":8082")
}

func getParam(c *gin.Context) {
	a := c.Query("a") //取参数a的值，取不到返回""
	fmt.Println(a)
	b := c.DefaultQuery("b", "b0") //取参数b的值，取不到返回defaultValue
	fmt.Println(b)
	cc, ok := c.GetQuery("c") //取参数c的值，取不到返回ok=false
	fmt.Println(cc, ok)

	c.String(200, "sucess")
}

func postParam(c *gin.Context) {
	a := c.PostForm("a") //取参数a的值，取不到返回""
	fmt.Println(a)
	b := c.DefaultPostForm("b", "b0") //取参数b的值，取不到返回defaultValue
	fmt.Println(b)
	cc, ok := c.GetPostForm("c") //取参数c的值，取不到返回ok=false
	fmt.Println(cc, ok)

	c.String(200, "sucess")
}

func urlParam(c *gin.Context) {
	id := c.Param("id")
	fmt.Println(id)

	c.String(200, "sucess")
}

func structParam(c *gin.Context) {
	u := User{}
	if err := c.ShouldBind(&u); err == nil {
		log.Println(u.Phone)
		log.Println(u.Age)
	}
	//返回成功
	c.String(200, "sucess")
}
